package com.hzlj.position.job.notice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fz.common.base.core.JsonUtils;
import com.fz.common.base.core.date.DateUtils;
import com.hzlj.common.message.common.dto.message.MessageNoticeResultDTO;
import com.hzlj.common.message.common.dto.message.MessageNoticeUserDTO;
import com.hzlj.common.message.common.util.MessageRestUtil;
import com.hzlj.position.config.common.enums.ReportType;
import com.hzlj.position.job.common.model.NoticeJob;
import com.hzlj.position.job.rest.StatRest;
import com.hzlj.position.locate.common.dto.reportCommon.ReportInspectionStatDTO;
import com.hzlj.position.locate.common.dto.reportInspectionAutoSetting.ReportInspectionAutoSettingQueryResultDTO;
import com.hzlj.position.locate.service.ReportInspectionAutoSettingService;
import com.hzlj.sqjz.login.common.dto.userAuth.UserAuthWithRyxxQueryResultDTO;
import com.hzlj.sqjz.login.service.UserAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ReportInspectionAutoNoticeJob implements BaseNoticeJob {
    @Resource
    private StatRest statRest;
    @Resource
    private ReportInspectionAutoSettingService reportInspectionAutoSettingService;
    @Resource
    private UserAuthService userAuthService;

    @Override
    public void notice(List<NoticeJob> jobs) {
        Date now = new Date();
        for (NoticeJob job : jobs) {
            List<ReportInspectionAutoSettingQueryResultDTO> settings = reportInspectionAutoSettingService.mostMatchedSetting4Sync(job.getJgCode(), now);
            if (ObjectUtil.isEmpty(settings)) {
                continue;
            }
            //匹配需要发送通知的任务
            settings = settings.stream().filter(e -> {
                Integer minutes = job.getParams().getInspectionAutoResultMinutes();
                Date noticeTime = DateUtil.offset(DateUtils.parseFixedHHmm(now, e.getEndTime()), DateField.MINUTE, minutes);
                return noticeTime.compareTo(job.getNextExeTime()) <= 0 && noticeTime.compareTo(job.getLastExeTime()) > 0;
            }).collect(Collectors.toList());
            if (ObjectUtil.isEmpty(settings)) {
                continue;
            }

            for (ReportInspectionAutoSettingQueryResultDTO setting : settings) {
                List<ReportInspectionStatDTO> stats = statRest.statInspectionAutoByReportStatus(job.getParams(), setting.getJgCode(), ReportType.AUTO.getCode(), now);
                //给角色发送
                for (ReportInspectionStatDTO stat : stats) {
                    try {
                        Map<String, Object> params = BeanUtil.beanToMap(stat);
                        params.put("belongDay", DateUtil.formatDate(now));
                        params.put("spotCheckTime", DateUtil.formatDateTime(now));
                        params.put("reportType", "zddy");
                        List<MessageNoticeResultDTO> result = MessageRestUtil.noticeQueryUsers(
                                "report-inspection-auto-result-gzry",
                                setting.getId(),
                                params,
                                MessageNoticeUserDTO.of(true, stat.getJgCode(), job.getRoles()));
                        log.info("自动点验结果通知(角色):notice={},stat={}", JsonUtils.obj2json(result), JsonUtils.obj2json(stat));
                    } catch (Exception e) {
                        log.error("自动点验结果通知异常(角色):notice={}", JsonUtils.obj2json(stat));
                    }
                }

                //给创建人发送
                if (ObjectUtil.isEmpty(setting.getCreatorUid()) || ObjectUtil.isEmpty(stats)) {
                    continue;
                }
                UserAuthWithRyxxQueryResultDTO userAuth = userAuthService.getUserAuthWithRyxx(null, setting.getCreatorUid());
                if (userAuth != null
                        && userAuth.getRoleAuths() != null
                        && ObjectUtil.isNotEmpty(CollectionUtil.intersection(userAuth.getRoleAuths(), Arrays.stream(job.getRoles().split(",")).collect(Collectors.toList())))) {
                    continue;
                }
                //合并结果
                ReportInspectionStatDTO stat = stats.get(0);
                for (int i = 1; i < stats.size(); i++) {
                    ReportInspectionStatDTO stat2 = stats.get(i);
                    stat.setInspectionAmt(stat.getInspectionAmt() + stat2.getInspectionAmt());
                    stat.setInspectionSuccessAmt(stat.getInspectionSuccessAmt() + stat2.getInspectionSuccessAmt());
                    stat.setInspectionNeverAmt(stat.getInspectionNeverAmt() + stat2.getInspectionNeverAmt());
                }
                try {
                    Map<String, Object> params = BeanUtil.beanToMap(stat);
                    params.put("belongDay", DateUtil.formatDate(now));
                    params.put("spotCheckTime", DateUtil.formatDateTime(now));
                    params.put("reportType", "zddy");
                    List<MessageNoticeResultDTO> result = MessageRestUtil.noticeQueryUsers(
                            "report-inspection-auto-result-gzry",
                            setting.getId(),
                            params,
                            MessageNoticeUserDTO.of(true, setting.getCreatorUid()));
                    log.info("自动点验结果通知(创建人):notice={},stat={}", JsonUtils.obj2json(result), JsonUtils.obj2json(stat));
                } catch (Exception e) {
                    log.error("自动点验结果通知异常(创建人):notice={}", JsonUtils.obj2json(stat));
                }

            }
        }
    }

}
